public class Solution900 {

    int[] target;
    int cur=0;

    public Solution900(int[] encoding) {
        target=encoding;
        target[0]++;
    }

    public int next(int n) {
        while (cur<target.length && (n>=target[cur]||target[cur]==0)){
            n-=target[cur];
            cur+=2;
        }
        if (cur==target.length){
            return -1;
        }else{
            target[cur]-=n;
            return target[cur+1];
        }
    }

    public static void main(String[] args) {
        Solution900 solution900=new Solution900(new int[]{3,8,0,9,2,5});
        System.out.println(solution900.next(2));
        System.out.println(solution900.next(1));
        System.out.println(solution900.next(1));
        System.out.println(solution900.next(2));
    }
}
